package pl.edu.agh.sius.gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import pl.edu.agh.sius.gui.model.SharedFilesTableModel;
import pl.edu.agh.sius.schema.simplep2pserver.FileInfo;

public class UploadJPanel extends JPanel{
	private static final long serialVersionUID = 8144948457752143394L;
	
	private SharedFilesTableModel sharedFilesTableModel;
	private FileInfo selectedFile;

	@SuppressWarnings("unused")
	private void init(){
		setLayout(new FlowLayout(FlowLayout.LEFT));
		
		JLabel filesTableTitle = new JLabel("Shared files list");
		JScrollPane sharedFilesTable = createSharedFilesTable();
		JButton addButton = new JButton("Add file");
		JButton removeButton = new JButton("Remove file");
		
		setPreferredSize(new Dimension(600, 300));
		
		add(filesTableTitle);
		add(sharedFilesTable);
		
		add(addButton);
		
	  	addButton.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		sharedFilesTableModel.addFile();
	    	}
	    });
		
	
		add(removeButton);
		
		removeButton.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		sharedFilesTableModel.removeFile(selectedFile);
	    	}
	    });
	}

	private JScrollPane createSharedFilesTable(){	
		JTable sharedFilesTable = new JTable(sharedFilesTableModel);
		sharedFilesTable.setFillsViewportHeight(true);
		
		sharedFilesTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if( javax.swing.SwingUtilities.isLeftMouseButton(e) ){
					int row = ((JTable)e.getSource()).getSelectedRow();
					selectedFile = (FileInfo)sharedFilesTableModel.getData(row);
				}
			}
		});
		
		JScrollPane sharedFilesTablePanel = new JScrollPane(sharedFilesTable);
		sharedFilesTablePanel.setPreferredSize(new Dimension(575, 200));
		
		return sharedFilesTablePanel;
	}

	public SharedFilesTableModel getSharedFilesTableModel() {
		return sharedFilesTableModel;
	}

	public void setSharedFilesTableModel(SharedFilesTableModel sharedFilesTableModel) {
		this.sharedFilesTableModel = sharedFilesTableModel;
	}

	public void setFilesData() {
		this.sharedFilesTableModel.setUserFilesData();
	}
}
